import React from 'react';
import {Spin, Card, Button, Table, Row, Col, Popover} from 'antd';
import DescriptionList from 'ant-design-pro/lib/DescriptionList';
import PropTypes from 'prop-types';
import {noticeImportant} from '../Enum';
import routes from './routes';
import {TABLE, FILES_API, DATETIME_FORMAT} from '../constants';
import {conventEnumValueToString, formatDateTime} from '../utils';
import WrappedPopconfirm from '../common/WrappedPopconfirm';
import {getDetail, abandonData, releaseData, cancelData} from './api';
import {injectIntl} from './intl';
import {hasPermissions} from './utils';
import {PERMISSION} from './constants';
import styles from './style.css';
const {Description} = DescriptionList;
class DetailPanel extends React.PureComponent {
    state = {
        isFetching: false,
        data: {},
        details: [],
        attachments: [],
    }
    componentDidMount() {
        this.getDetailInfo();
    }
    getDetailInfo = () => {
        const id = this.props.id;
        this.setState({isFetching: true});
        getDetail(id)
            .then(res => {
                if(res.ok)
                    this.setState({
                        isFetching: false,
                        data: res.data,
                        details: res.data.details,
                        attachments: res.data.attachments
                    });
                else
                    this.setState(({
                        isFetching: false
                    }));
            });
    }
    onClickReleaseBtn = () => {
        this.setState({loading: true});
        const data = {
            rowVersion: this.state.data.rowVersion
        };
        releaseData(this.state.data.id, data)
            .then(res => {
                this.setState({loading: false});
                if(res.ok)
                    this.props.successReturn();
            });
    }
    onClickCancleBtn = () => {
        this.setState({loading: true});
        const data = {
            rowVersion: this.state.data.rowVersion
        };
        cancelData(this.state.data.id, data)
            .then(res => {
                this.setState({loading: false});
                if(res.ok)
                    this.props.successReturn();
            });
    }
    onClickAbandon = () => {
        this.setState({loading: true});
        const data = {
            rowVersion: this.state.data.rowVersion
        };
        abandonData(this.state.data.id, data)
            .then(res => {
                this.setState({loading: false});
                if(res.ok)
                    this.props.successReturn();
            });
    }
    onCancel = () => {
        this.props.history.push(routes.query.url());
    }
    render() {
        const {data, details, attachments} = this.state;
        const {formatMessage} = this.props.intl;
        const operations = [];
        if(hasPermissions(this.props.permissions, PERMISSION.update) && hasPermissions(data.options, PERMISSION.update))
            operations.push(<Button key="update" href={`#${routes.update.format(this.props.id)}`} size="small">{
                formatMessage({
                    id: 'detailPanel.update',
                    defaultMessage: '修改'
                })
            }</Button>);
        if(hasPermissions(this.props.permissions, PERMISSION.signfor) && hasPermissions(data.options, PERMISSION.signfor))
            operations.push(<Button key="signfor" href={`#${routes.signfor.format(this.props.id)}`} size="small">{
                formatMessage({
                    id: 'detailPanel.signfor',
                    defaultMessage: '签收回复'
                })
            }</Button>);
        if(hasPermissions(this.props.permissions, PERMISSION.release) && hasPermissions(data.options, PERMISSION.release))
            operations.push(<WrappedPopconfirm
                key="release"
                id={this.props.id}
                placement="topLeft"
                onConfirm={this.onClickReleaseBtn}
                title={formatMessage({
                    id: 'detailPanel.validate.release',
                    defaultMessage: '是否确认发布？'
                })}>
                <Button key="release" size="small">{
                    formatMessage({
                        id: 'detailPanel.release',
                        defaultMessage: '发布'
                    })
                }</Button>
            </WrappedPopconfirm>);
        if(hasPermissions(this.props.permissions, PERMISSION.cancel) && hasPermissions(data.options, PERMISSION.cancel))
            operations.push(<WrappedPopconfirm
                key="cancel"
                id={this.props.id}
                placement="topLeft"
                onConfirm={this.onClickCancleBtn}
                title={formatMessage({
                    id: 'detailPanel.validate.cancel',
                    defaultMessage: '是否确认取消发布？'
                })}>
                <Button key="cancel" size="small">{
                    formatMessage({
                        id: 'detailPanel.cancel',
                        defaultMessage: '取消发布'
                    })
                }</Button>
            </WrappedPopconfirm>);
        if(hasPermissions(this.props.permissions, PERMISSION.abandon) && hasPermissions(data.options, PERMISSION.abandon))
            operations.push(<WrappedPopconfirm
                key="abandon"
                id={this.props.id}
                placement="topLeft"
                onConfirm={this.onClickAbandon}
                title={formatMessage({
                    id: 'detailPanel.validate.abandon',
                    defaultMessage: '是否确认作废？'
                })}>
                <Button key="abandon" size="small">{
                    formatMessage({
                        id: 'detailPanel.abandon',
                        defaultMessage: '作废'
                    })
                }</Button>
            </WrappedPopconfirm>);

        const columns = [
            {
                title: formatMessage({
                    id: 'detailPanel.column.isSigned',
                    defaultMessage: '是否签收'
                }),
                dataIndex: 'isSigned',
                render: (text, record) => record.isSigned ? formatMessage({
                    id: 'detailPanel.column.yes',
                    defaultMessage: '是'
                }) : formatMessage({
                    id: 'detailPanel.column.no',
                    defaultMessage: '否'
                })
            }, {
                title: formatMessage({
                    id: 'detailPanel.column.signedTime',
                    defaultMessage: '签收时间'
                }),
                dataIndex: 'signedTime',
                render: text => formatDateTime(text, DATETIME_FORMAT)
            }, {
                title: formatMessage({
                    id: 'detailPanel.column.isReplied',
                    defaultMessage: '是否回复'
                }),
                dataIndex: 'isReplied',
                render: (text, record) => record.isReplied ? formatMessage({
                    id: 'detailPanel.column.yes',
                    defaultMessage: '是'
                }) : formatMessage({
                    id: 'detailPanel.column.no',
                    defaultMessage: '否'
                })
            }, {
                title: formatMessage({
                    id: 'detailPanel.column.repiiedTime',
                    defaultMessage: '回复时间'
                }),
                dataIndex: 'repiiedTime',
                render: text => formatDateTime(text, DATETIME_FORMAT)
            }, {
                title: formatMessage({
                    id: 'detailPanel.column.replyContent',
                    defaultMessage: '回复内容'
                }),
                dataIndex: 'replyContent',
            }, {
                title: this.props.intl.formatMessage({
                    id: 'detailPanel.column.action',
                    defaultMessage: '操作'
                }),
                dataIndex: 'action',
                render: (text, record) => {
                    const {attachments = []} = record;
                    if(!attachments.length)
                        return '';
                    const fileList = attachments.map(item => (<Description key={item.fileId}><a icon="download" href={`${FILES_API.files}/${item.fileId}`} size="small">
                        {item.fileName}</a></Description>));
                    return (<Popover trigger="click" content={<DescriptionList col={1} size="large">
                        {fileList}
                    </DescriptionList>}>
                        <a icon="download" size="small">
                            {this.props.intl.formatMessage({
                                id: 'detailPanel.downloadFile',
                                defaultMessage: '下载附件'
                            })}</a>
                    </Popover>);
                }
            }];
        if(!this.props.isDealerUser)
            columns.splice(1, 0,
                {
                    title: this.props.intl.formatMessage({
                        id: 'detailPanel.column.dealerCode',
                        defaultMessage: '总代/KD工厂'
                    }),
                    dataIndex: 'dealerCode',
                });
        return (
            <div>
                <Spin spinning={this.state.isFetching}>
                    <Card>
                        <DescriptionList size="large" title={<Row><Col span={6}>{
                            formatMessage({
                                id: 'detailPanel.card.notice',
                                defaultMessage: '通知通告详情主单'
                            })
                        }</Col>
                        <Col className={`col-align-right ${styles.detail}`} span={18}>{operations}</Col>
                        </Row>}>
                            <Description term={formatMessage({
                                id: 'detailPanel.operation.code',
                                defaultMessage: '编号'
                            })}>{data.code}
                            </Description>
                            <Description term={formatMessage({
                                id: 'detailPanel.operation.name',
                                defaultMessage: '主题'
                            })}>{data.name}
                            </Description>
                            <Description term={formatMessage({
                                id: 'detailPanel.operation.programName',
                                defaultMessage: '栏目'
                            })}>{data.programName}
                            </Description>
                            <Description term={formatMessage({
                                id: 'detailPanel.operation.important',
                                defaultMessage: '重要度'
                            })}>{conventEnumValueToString(noticeImportant, data.important)}
                            </Description>
                            <Description term={formatMessage({
                                id: 'detailPanel.operation.isNeedReply',
                                defaultMessage: '是否需要回复'
                            })}>{data.isNeedReply ? formatMessage({
                                    id: 'detailPanel.operation.yes',
                                    defaultMessage: '是'
                                }) : formatMessage({
                                    id: 'detailPanel.operation.no',
                                    defaultMessage: '否'
                                })}
                            </Description>
                            <Description term={formatMessage({
                                id: 'detailPanel.operation.content',
                                defaultMessage: '内容'
                            })}>{data.content}
                            </Description>
                        </DescriptionList>
                    </Card>
                    <Card>
                        {attachments && attachments.length >= 0
                            ? <DescriptionList size="large" title={formatMessage({
                                id: 'detailPanel.card.attachment',
                                defaultMessage: '主单附件'
                            })}>
                                {attachments.map(item => (<Description key={item.fileId}>
                                    <a icon="download" download href={`${FILES_API.files}/${item.fileId}`} size="small">
                                        {item.fileName}</a></Description>))}
                            </DescriptionList>
                            : <DescriptionList size="large" title={formatMessage({
                                id: 'detailPanel.content.noAttachment',
                                defaultMessage: '暂无附件'
                            })}>
                            </DescriptionList>}
                    </Card>
                    <Card>
                        <DescriptionList size="large" title={formatMessage({
                            id: 'detailPanel.table.details',
                            defaultMessage: '通知通告详情清单'
                        })}>
                            <Table
                                className="white-space-nowrap"
                                columns={columns}
                                rowKey="id"
                                pagination={false}
                                dataSource={details}
                                {...TABLE} />
                        </DescriptionList>
                    </Card>
                </Spin>
                <div className="page-toolbar">
                    <Button type="primary" onClick={this.onCancel}>{this.props.intl.formatMessage({
                        id: 'detailPanel.operation.onCancel',
                        defaultMessage: '返回'
                    })}</Button>
                </div>
            </div>
        );
    }
}

DetailPanel.propTypes = {
    history: PropTypes.object,
    id: PropTypes.string,
    intl: PropTypes.object,
    isDealerUser: PropTypes.bool,
    permissions: PropTypes.array
};

import {connect} from 'react-redux';
import {
    tableSearch,
} from './actions';
import selectorFactory from 'Shared/utils/immutableToJsSelectorFactory';
const getPermissions = selectorFactory(['page', 'domainData', 'permission', 'data']);
const mapStateToProps = state => ({
    isDealerUser: state.getIn((['page', 'domainData', 'initData', 'isDealerUser'])),
    permissions: getPermissions(state)
});
const mapDispatchToProps = (dispatch, props) => ({
    successReturn: () => {
        dispatch(tableSearch());
        props.history.push(routes.query.url());
    },
    onCancel: () => {
        props.history.push(routes.query.url());
    },
});
export default connect(mapStateToProps, mapDispatchToProps)(injectIntl(DetailPanel));
